package com.hp.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hp.entity.Employee;
import com.hp.entity.ExceptionJSONInfo;
import com.hp.exception.EmployeeNotFoundException;

/**
 * http://www.journaldev.com/2651/spring-mvc-exception-handling-exceptionhandler-controlleradvice-handlerexceptionresolver-json-response-example
 */

@Controller
public class EmployeeController {

	@RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
	public String getEmployee(@PathVariable("id") int id, Model model)
			throws Exception {
		if (id == 1) {
			throw new EmployeeNotFoundException(id);
		} else if (id == 2) {
			throw new SQLException("SQLException, id=" + id);
		} else if (id == 3) {
			throw new IOException("IOException, id=" + id);
		} else if (id == 10) {
			Employee emp = new Employee();
			emp.setName("Jarvan");
			emp.setId(id);
			model.addAttribute("employee", emp);
			return "home";
		} else {
			throw new Exception("Generic Exception, id=" + id);
		}

	}

	//@ExceptionHandler(EmployeeNotFoundException.class)
	public ModelAndView handleEmployeeNotFoundException(
			HttpServletRequest request, Exception ex) {
		
		System.out.println("开始异常处理");

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("exception", ex);
		modelAndView.addObject("url", request.getRequestURL());

		modelAndView.setViewName("error");
		return modelAndView;
	}
	
	@ExceptionHandler(EmployeeNotFoundException.class)
	@ResponseBody 
	public ExceptionJSONInfo handleEmployeeNotFoundException2(HttpServletRequest request, Exception ex){
	     
	    ExceptionJSONInfo response = new ExceptionJSONInfo();
	    response.setUrl(request.getRequestURL().toString());
	    response.setMessage(ex.getMessage());
	     
	    return response;
	}
}
